package com.arpa.wms.controller.wms;

import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.dto.ReceiptDTO;
import com.arpa.wms.domain.dto.ReceiptEditDTO;
import com.arpa.wms.domain.entity.Receipt;
import com.arpa.wms.domain.vo.ReceiptVO;
import com.arpa.wms.service.IReceiptService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * <p>
 * 仓库收款单 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-11-17
 */
@Api(tags = "仓库收款单")
@RestController
@RequestMapping(value = "/receipt", produces = "application/json;charset=UTF-8")
@Log4j2
public class ReceiptController {

    private final IReceiptService iReceiptService;

    @Resource
    private RedissonClient redissonClient;

    public ReceiptController(IReceiptService iReceiptService) {
        this.iReceiptService = iReceiptService;
    }

    /**
     * 获取 仓库收款单 列表
     *
     * @param receiptDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取WMS收款单列表", notes = "获取WMS收款单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "gmtCreatedStart", value = "创建日期起", paramType = "query", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "gmtCreatedEnd", value = "创建日期止", paramType = "query", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "gmtModifiedStart", value = "修改日期起", paramType = "query", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "gmtModifiedEnd", value = "修改日期止", paramType = "query", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "createdName", value = "创建人", paramType = "query", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "modifiedName", value = "修改人", paramType = "query", dataType = "string", defaultValue = ""),
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ReceiptVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(ReceiptDTO receiptDTO, HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            //登录账号授权的仓库过滤
            receiptDTO.setWarehouseCodes(UserUtil.getAuthorizeWarehouseCodes());
            //登录账号授权的货主过滤
            receiptDTO.setShipmentCodes(UserUtil.getAuthorizeShipmentCodes());
            receiptDTO.setGroupCode(UserUtil.getBranchCode());
            ReceiptVO receiptVoSum = iReceiptService.queryListSum(receiptDTO);
            List<ReceiptVO> receiptVOList = iReceiptService.queryList(receiptDTO);

            Page returnPage = new Page(receiptDTO.getPageNum(), receiptDTO.getPageSize());
            returnPage.setRecords(receiptVOList);
            returnPage.setTotal(receiptVoSum.getTotal());
            returnPage.setSumObject(receiptVoSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 获取仓库收款单详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取WMS收款单详情", notes = "获取WMS收款单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "仓库收款单code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ReceiptVO.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result receipt(@PathVariable String code, HttpServletRequest request) {
        try {
            ReceiptVO receiptVO =  iReceiptService.getReceipt(code);
            return Result.ok().data(receiptVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改仓库收款单
     * 只有新增状态下才可以编辑
     *
     * @param entity  仓库收款单
     * @param request
     * @return
     */
    @ApiOperation(value = "修改仓库收款单", notes = "只有新增状态才可以编辑")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Validated ReceiptEditDTO entity,   HttpServletRequest request) {
        if (StringUtils.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }
        RLock l = null;
        try {
            String code = entity.getCode();
            l = redissonClient.getLock(getReceiptCodeKey(code));
            if (l.tryLock()) {
                Receipt receipt = iReceiptService.getOne(new QueryWrapper<Receipt>().lambda().eq(Receipt::getCode, code).eq(Receipt::getGroupCode,UserUtil.getBranchCode()));
                if (null == receipt) {
                    return Result.error("收款单【" + code + "】修改失败，找不到收款单");
                }
                if (!StrUtil.equals("0", receipt.getStatus())) {
                    return Result.error("收款单【" + code + "】修改失败，当前状态不能修改");
                }
                log.info("修改收款单【{}】获得锁", code);
                entity.setStatus("0");
                iReceiptService.update(entity);
                return Result.ok("收款单修改成功！");
            } else {
                log.error("收款单【{}】修改失败，正在操作中", code);
                return Result.error("收款单【" + code + "】修改失败，正在操作中");
            }
        } catch (Exception ex) {
            log.error(StrConsts.CATCH_MESSAGE,ex);
            return Result.error(ex.getMessage());
        } finally {
            try {
                if (null != l && l.isLocked()) {
                    l.unlock();
                }
            } catch (Exception e) {
                log.error("释放锁失败！！", e);
            }
        }
    }


    /**
     * 提交收款单
     *
     * @param entity  收款单
     * @param request
     * @return
     */
    @ApiOperation(value = "提交收款单 ", notes = "提交收款单更改为待审核状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PostMapping("/submit")
    public Result submit(@RequestBody @Validated ReceiptEditDTO entity, HttpServletRequest request) {
        if (StringUtils.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }
        RLock l = null;
        try {
            String code = entity.getCode();
            l = redissonClient.getLock(getReceiptCodeKey(code));
            if (l.tryLock()) {
                Receipt receipt = iReceiptService.getOne(new QueryWrapper<Receipt>().lambda().eq(Receipt::getCode, code).eq(Receipt::getGroupCode,UserUtil.getBranchCode()));
                if (null == receipt) {
                    return Result.error("收款单【" + code + "】提交失败，找不到收款单");
                }
                if (!StringUtils.equals("0", receipt.getStatus())) {
                    return Result.error("收款单【" + code + "】提交失败，当前状态不能提交");
                }
                log.info("提交收款单【{}】获得锁", code);

                entity.setStatus("1");
                iReceiptService.update(entity);
                return Result.ok("收款单提交成功！");
            } else {
                log.error("收款单【{}】提交失败，正在操作中", code);
                return Result.error("收款单【" + code + "】提交失败，正在操作中");
            }
        } catch (Exception ex) {
            log.error(StrConsts.CATCH_MESSAGE,ex);
            return Result.error(ex.getMessage());
        } finally {
            try {
                if (null != l && l.isLocked()) {
                    l.unlock();
                }
            } catch (Exception e) {
                log.error("释放锁失败！！", e);
            }
        }
    }


    /**
     * 删除 仓库收款单
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 仓库收款单 ", notes = "删除 仓库收款单 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "仓库收款单code", paramType = "path", dataType = "String"),
    })
    @NeedLogin
    @DeleteMapping(value = "/{code}")
    public Result delete(@PathVariable String code, HttpServletRequest request) {
        try {
            iReceiptService.removeByCode(code);
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 收款单审核
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "收款单审核", notes = "收款单审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "仓库收款单code", paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "审核状态：1通过，2不通过", required = true, paramType = "query", dataType = "Integer", defaultValue = "1"),
            @ApiImplicitParam(name = "verifyOpinion", value = "审核意见", required = false, paramType = "query", dataType = "String"),
    })
    @NeedLogin
    @PutMapping("/approve/{code}")
    public Result approveFail(@PathVariable String code,@RequestParam("status") int status, @RequestParam(value = "verifyOpinion",defaultValue = "") String verifyOpinion, HttpServletRequest request) {
        try {
            if(StringUtils.isBlank(code)){
                return Result.error("code不能为空");
            }
            boolean updateNum = iReceiptService.approve(code,status,verifyOpinion);
            if(updateNum) {
                return Result.ok("收款单审核成功！");
            }else{
                return Result.error("收款单审核失败！");
            }
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    private String getReceiptCodeKey(String code) {
        return String.format("receipt-op-%s", code);
    }

}
